package nl.mkmedia.tuio.behaviours {
	import nl.mkmedia.tuio.TUIOPoint;
	import flash.display.DisplayObject;
	import flash.geom.Point;

	/**
	 * @author Mingoes Kukupessy (mingoes at gmail dot com)
	 */
	public class BMultipleFingerScale {
		
		public static function callback(points:Array, displayObject:DisplayObject):void
		{
			if(points.length > 1) {
				var averageLengths:Array = getAverageLengths(getCenterPoint(points), points);
				for each (var point : TUIOPoint in points) { if (point.oldX == 0 || point.oldY == 0) return; }	
				displayObject.scaleX = displayObject.scaleY *=  averageLengths[1] / averageLengths[0];
			}
		}
		
		public static function getCenterPoint(points:Array):Point
		{
			var i : int = points.length, sumX:Number = 0, sumY:Number = 0;
			while(i--){
				sumX += (points[i] as TUIOPoint).x;
				sumY += (points[i] as TUIOPoint).y;
			}
			return new Point(sumX / points.length, sumY / points.length);
		}
		
		public static function getAverageLengths(center:Point, points:Array):Array
		{
			var i : int = points.length, oldLengths:Number = 0, newLengths:Number = 0;
			while(i--){
				oldLengths += Point.distance(center, new Point(points[i].oldX, points[i].oldY));
				newLengths += Point.distance(center, new Point(points[i].x, points[i].y));
			}
			return [oldLengths / points.length, newLengths / points.length];
		}
	}
}